package com.xieman.anti.replay.utils.bean;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.NonNull;

import java.lang.annotation.Annotation;
import java.util.Map;

/**
 * @description Bean Factory
 * @author gaopengsui@creditease.cn
 * @date 2021/09/09 17:58
 */
public class BeanFactory implements ApplicationContextAware {

  private static ApplicationContext context;

  @Override
  public void setApplicationContext(@NonNull ApplicationContext context) throws BeansException {
    setAppContext(context);
  }

  private synchronized void setAppContext(ApplicationContext context) {
    BeanFactory.context = context;
  }

  public static ApplicationContext getApplicationContext() {
    return context;
  }

  public static Object getBean(String name) {
    return context.getBean(name);
  }

  public static <T> T getBean(Class<T> clazz) {
    return context.getBean(clazz);
  }

  public static <T> T getBean(String name, Class<T> clazz) {
    return context.getBean(name, clazz);
  }

  public static Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> clazz) {
    return context.getBeansWithAnnotation(clazz);
  }

  public static Map<String, ?> getBeansWithType(Class<?> clazz) {
    return context.getBeansOfType(clazz);
  }
}
